package cms.web.tag;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import cms.bean.forumCode.ForumCodeReference;
import cms.utils.threadLocal.TemplateThreadLocal;
import freemarker.core.Environment;
import freemarker.core.ParseException;
import freemarker.template.Template;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import static cms.common.SystemConstant.ENCODING_UTF8;
import static cms.common.SystemConstant.TemplateTag.INCLUDE;

/**
 * 自定义引入指令Include
 *
 */
@Slf4j
public class TemplateIncludeMethods extends BaseTemplateMethods implements TemplateDirectiveModel {
	/**
	 * @param env
	 * @param params 参数
	 * @param loopVars 循环变量
	 * @param body 指令内容体
	 */
	@Override
	public void doExecute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
//		String referenceCode = "";//版块引用代码   ProductRelated_Product_3
//
//		String modulePath = "";//模块路径      templates/bbb/Forum/ProductRelated_Product_Multilayer_Default.html
		ForumCodeReference forumCodeReference = forumCodeReferenceAction(params,INCLUDE.getLabel());
		if(forumCodeReference==null){
			throw new TemplateException("自定义引入指令Include，没有包含"+INCLUDE.getLabel()+"标签或引用不存在", env);
		}
		setTemplateThreadLocal(params);

		boolean parse = true;

        TemplateThreadLocal.setReferenceCode(forumCodeReference.getReferenceCode());
        
        Template includedTemplate;
        try {
            includedTemplate = env.getTemplateForInclusion(forumCodeReference.getForumPath(), ENCODING_UTF8, parse);
        }catch (ParseException pe) {
            String msg = "错误解析包含的模板 "+ forumCodeReference.getForumPath()  + "\n" + pe.getMessage();
            throw new TemplateException(msg, pe, env);
        }catch (IOException ioe) {
            String msg = "包含的文件读取错误 "+ forumCodeReference.getForumPath();
            throw new TemplateException(msg, ioe, env);
        }catch (Exception e){
			String msg = "包含的文件其他错误"+ forumCodeReference.getForumPath();
			throw new TemplateException(msg, e, env);
		}
        env.include(includedTemplate);
	}

	/**
	 * 将当前正在运行的引入指令设进模板参数里面
	 * @param params
	 */
	private void setTemplateThreadLocal(Map params) {
		if(MapUtils.isNotEmpty(params)) {
			Iterator paramIter = params.entrySet().iterator();
			while (paramIter.hasNext()) {
				Map.Entry ent = (Map.Entry) paramIter.next();
				String key = (ent.getKey() + "").trim();
				if (StringUtils.isNotBlank(key)) {
					String value = (ent.getValue() + "").trim();
					if (StringUtils.isNotBlank(value)) {
						TemplateThreadLocal.addParameter(key, value);
					}
				}
			}
		}
	}
}
